<?php

class kelola_gambar{
	
	function __construct(){
			
		$db_config = new db_config();
		
		$link = mysql_connect($db_config->host.':'.$db_config->port, $db_config->db_username, $db_config->db_password);
		
		if (!$link) {
			die('Could not connect: '.mysql_error());
		}
		
		if(!mysql_select_db($db_config->db_name)) {
			die("cannot select db");
		}
		
	}
	
	function insert_gambar($data){
		
		extract($data, EXTR_OVERWRITE);
		
		$sql = '
			INSERT INTO 
				gambar 
				(ID_PRODUK, URL, DESKRIPSI_GAMBAR) 
			VALUES
				('.$ID_PRODUK.',"'.$URL.'","'.$DESKRIPSI_GAMBAR.'")
		';
		
		mysql_query($sql);
		
		$id_gambar = mysql_insert_id();
		
		return $id_gambar;
		
	}
	
	
	function update_gambar($id_gambar, $deskripsi){
		
		$sql = '
			UPDATE 
				gambar  
			SET 
				DESKRIPSI_GAMBAR = "'.$deskripsi.'" 
			WHERE
				ID_GAMBAR = '.$id_gambar.'
		';
		
		$query = mysql_query($sql);
		
	}
	
	function select_gambar_isi($id_gambar){
		
		$sql = '
			SELECT *
			FROM
				gambar
			WHERE
				ID_GAMBAR = '.$id_gambar.'
		';
		
		$query = mysql_query($sql);
		
		return $query;
		
	}
	
	function select_gambar($id_produk){
		
		$sql = '
			SELECT *
			FROM
				gambar
			WHERE
				ID_PRODUK = '.$id_produk.'
		';
		
		$query = mysql_query($sql);
		
		return $query;
		
	}
	
	function select_gambar_limit($id_produk, $limit){
		
		$sql = '
			SELECT *
			FROM
				gambar
			WHERE
				ID_PRODUK = '.$id_produk.' 
			LIMIT '.$limit.'
		';
		
		$query = mysql_query($sql);
		
		return $query;
		
	}
	
	function select_gambar_technopreneur($id_technopreneur){
		
		$sql = '
			SELECT 
				at.ID_TECHNOPRENEUR, p.ID_PRODUK, g.URL, g.DESKRIPSI_GAMBAR 
			FROM 
				gambar as g left join produk as p on g.ID_PRODUK=p.ID_PRODUK left join account_technopreneur as at on at.ID_TECHNOPRENEUR=p.ID_TECHNOPRENEUR 
			WHERE 
				at.ID_TECHNOPRENEUR='.$id_technopreneur.'
		';
		
		$query = mysql_query($sql);
		
		return $query;
		
	}
	
	function delete_gambar($id_gambar){		
		
		$res = $this->select_gambar_isi($id_gambar);
		
		$gambar = mysql_fetch_assoc($res);
		
		unlink($gambar['URL']);
		
		$sql = '
			DELETE FROM
				gambar 
			WHERE
				ID_GAMBAR = '.$id_gambar.'
		';
		
		mysql_query($sql);
		
	}
	
	function delete_all_gambar($id_produk){
		
		$res = $this->select_gambar($id_produk);
		
		while($row = mysql_fetch_assoc($res)){
			unlink($row['URL']);
		}
		
		$sql = '
			DELETE FROM
				gambar 
			WHERE
				ID_PRODUK = '.$id_produk.'
		';
		
		mysql_query($sql);
		
	}

}